var location = window.location.toString(); 
var root     = location.indexOf("/id/") == -1 ? "../" : root = "../../";
var folder   = $("input#"+$("#jsfolder div").attr("class")).val();
var JSEditorOptions = { 
		target:       '#avisos',
		success:      show_JSEditorResponse,
		url:          root + 'add-to-folder/folder/' + folder
};

function save_legenda()
{
	dados = "";
	$(".folder li").each(function(i)
	{
		obj = $(this).attr("id");
		dados += "legenda[]="+$("#" + obj + " input").val()      + "&";
		dados += "file[]="   +$("#" + obj + " input").attr("id") + "&";
	});
	
	$.post(root + "save-legend/folder/"+ folder,dados, function(data){});
}

function show_JSEditorResponse(responseText, statusText)
{
	show_aviso(responseText);
	get_JSEditorJson();
}
get_JSEditorJson();
function get_JSEditorJson()
{
	$.getJSON(root + 'list-folder/folder/' + folder, function(data)
	{
		var xhtml = "<ul class='folder'>";
		var arr = data;
		
		for(var i = 0; i < arr.length; i++)
		{
			xhtml +="<li id='file"+ i +"'>" +
						"<a href='/public/uploads/"+folder+"/"+arr[i].file+"' class='lightbox'>" +
							"<img src='/public/uploads/"+folder+"/temp/nadeb-temp-"+arr[i].file+"' heigth='100' width='100' />" +
						"</a>" +
						"<input type='text' name='legenda' id='"+arr[i].file+"' value='"+arr[i].legenda+"' />" +
						"<a href='" + root + "del-to-folder/folder/"+folder+"/file/"+arr[i].file.replace(".","/ext/")+"' class='excluir deleteFiles'>[x]</a>" +
					"</li>"
		}
		xhtml += "</ul>";
		$("#jsfolder div div").html(xhtml);
	});
};

$('.addfolder').click(function()
{
	$("form").ajaxSubmit(JSEditorOptions);
});

$(".deleteFiles").live("click",function()
{
	url = $(this).attr("href");
	$(this).parent("li").remove();
	
	$.post(url, function(data)
	{
		save_legenda();
		show_aviso(data);
	});
	
	return false;
});

$(".save_legend").click(function()
{
	show_aviso("Legendas salvas som sucesso!");
	save_legenda();		
	return false;
	
});